#include "main.h"

void lcd_init(void)
{
	GPIO_Init(GPIOA, LCD_CS, GPIO_MODE_OUT_PP_LOW_FAST);
	GPIO_Init(GPIOA, LCD_SDA, GPIO_MODE_OUT_PP_LOW_FAST);
	GPIO_Init(GPIOA, LCD_SCK, GPIO_MODE_OUT_PP_LOW_FAST);
	GPIO_Init(GPIOD, LCD_RST, GPIO_MODE_OUT_PP_LOW_FAST);

	GPIO_WriteLow(GPIOD,LCD_RST);
	delay(100);
	GPIO_WriteHigh(GPIOD,LCD_RST);
	delay(20000);
	lcd_send_cmd(0x30);
	delay(50);
	lcd_send_cmd(0x0C);
	delay(50);
}

void lcd_send_byte(uint8_t byte)
{
	uint8_t i, num;
	num = byte;
	for(i=0;i<8;i++)
	{
		if(num&0x80)
			GPIO_WriteHigh(GPIOA,LCD_SDA);
		else
			GPIO_WriteLow(GPIOA,LCD_SDA);
		GPIO_WriteLow(GPIOA,LCD_SCK);
		GPIO_WriteHigh(GPIOA,LCD_SCK);
		num = num<<1;
	}
}

void lcd_set_row(uint8_t row)
{
	switch(row){
		case 0: lcd_send_cmd(0x80); break;
		case 1: lcd_send_cmd(0x90); break;
		case 2: lcd_send_cmd(0x88); break;
		case 3: lcd_send_cmd(0x98); break;
	}
}

void delay(uint32_t t)
{
	uint32_t i,j;
	for(i=0; i<t;  i++)
    for(j=0; j<10; j++);
}

void lcd_send_cmd(uint8_t cmd)
{
	GPIO_WriteHigh(GPIOA,LCD_CS);
	lcd_send_byte(0xF8);
	lcd_send_byte(cmd&0xF0);
	lcd_send_byte((cmd<<4)&0xF0);
	GPIO_WriteLow(GPIOA,LCD_CS);
}

void lcd_send_data(uint8_t data)
{
	GPIO_WriteHigh(GPIOA,LCD_CS);
	lcd_send_byte(0xFA);
	lcd_send_byte(data&0xF0);
	lcd_send_byte((data<<4)&0xF0);
	GPIO_WriteLow(GPIOA,LCD_CS);
}

void lcd_print(uint8_t const *s)
{
	while(*s>0)
	{
		lcd_send_data(*s);
		s++;
	}
}

